<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>利用Sympy求解常系数微分方程 | Von Brank</title><meta name="keywords" content="教程,Python"><meta name="author" content="Von Brank"><meta name="copyright" content="Von Brank"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="昨天接到一个需求，要求用Python实现求解常系数微分方程，虽然后来咕掉了，但是让我发现了Sympy这个科学计算库竟然有如此神奇的功能。本文将介绍如何用Sympy解决初值问题。 先决条件 Anaconda先决条件 我们强烈建议您使用免费的Anaconda Python发行版，该发行版为您处理如Numpy, Sympy, Scipy等软件包依赖项提供了一种简便的方法。 你可以参考 这篇文章 来部署A">
<meta property="og:type" content="article">
<meta property="og:title" content="利用Sympy求解常系数微分方程">
<meta property="og:url" content="https://vonbrank.github.io/archives/sympy-solve-differential-equation/index.html">
<meta property="og:site_name" content="Von Brank">
<meta property="og:description" content="昨天接到一个需求，要求用Python实现求解常系数微分方程，虽然后来咕掉了，但是让我发现了Sympy这个科学计算库竟然有如此神奇的功能。本文将介绍如何用Sympy解决初值问题。 先决条件 Anaconda先决条件 我们强烈建议您使用免费的Anaconda Python发行版，该发行版为您处理如Numpy, Sympy, Scipy等软件包依赖项提供了一种简便的方法。 你可以参考 这篇文章 来部署A">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://z3.ax1x.com/2021/04/26/gSWYgs.md.png">
<meta property="article:published_time" content="2021-04-26T07:44:45.000Z">
<meta property="article:modified_time" content="2022-05-17T05:59:38.868Z">
<meta property="article:author" content="Von Brank">
<meta property="article:tag" content="教程">
<meta property="article:tag" content="Python">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://z3.ax1x.com/2021/04/26/gSWYgs.md.png"><link rel="shortcut icon" href="https://s2.loli.net/2022/01/08/s8FYlS5uPrtichT.jpg"><link rel="canonical" href="https://vonbrank.github.io/archives/sympy-solve-differential-equation/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"简"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#121212","position":"bottom-left"},
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isanchor: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '利用Sympy求解常系数微分方程',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-05-17 13:59:38'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          const now = new Date()
          const hour = now.getHours()
          const isNight = hour <= 6 || hour >= 18
          if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
          else if (t === 'light') activateLightMode()
          else activateDarkMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="Von Brank" type="application/atom+xml">
</head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="https://s2.loli.net/2022/01/08/s8FYlS5uPrtichT.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/archives/"><div class="headline">文章</div><div class="length-num">46</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/tags/"><div class="headline">标签</div><div class="length-num">25</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/categories/"><div class="headline">分类</div><div class="length-num">19</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/comments/"><i class="fa-fw fas fa-comments"></i><span> 评论</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-tools"></i><span> 工具</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="https://vonbrank.github.io/hit-introduction-to-discrete-mathematics/"><i class="fa-fw fas fa-less-than-equal"></i><span> 《离散数学引论》答案补充</span></a></li><li><a class="site-page child" href="https://vonbrank.github.io/my-tech-companies-website/"><i class="fa-fw fas fa-server"></i><span> 科技公司网页模仿</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://z3.ax1x.com/2021/04/26/gSWYgs.md.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/">Von Brank</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/comments/"><i class="fa-fw fas fa-comments"></i><span> 评论</span></a></div><div class="menus_item"><a class="site-page" href="javascript:void(0);"><i class="fa-fw fas fa-tools"></i><span> 工具</span><i class="fas fa-chevron-down expand"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="https://vonbrank.github.io/hit-introduction-to-discrete-mathematics/"><i class="fa-fw fas fa-less-than-equal"></i><span> 《离散数学引论》答案补充</span></a></li><li><a class="site-page child" href="https://vonbrank.github.io/my-tech-companies-website/"><i class="fa-fw fas fa-server"></i><span> 科技公司网页模仿</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">利用Sympy求解常系数微分方程</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-04-26T07:44:45.000Z" title="发表于 2021-04-26 15:44:45">2021-04-26</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-05-17T05:59:38.868Z" title="更新于 2022-05-17 13:59:38">2022-05-17</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Python/">Python</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">835</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>3分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="利用Sympy求解常系数微分方程"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><p>昨天接到一个需求，要求用Python实现求解常系数微分方程，虽然后来咕掉了，但是让我发现了Sympy这个科学计算库竟然有如此神奇的功能。本文将介绍如何用Sympy解决初值问题。</p>
<h2 id="先决条件">先决条件</h2>
<h3 id="Anaconda先决条件">Anaconda先决条件</h3>
<p>我们强烈建议您使用免费的<a target="_blank" rel="noopener" href="https://www.anaconda.com/download/">Anaconda Python发行版</a>，该<a target="_blank" rel="noopener" href="https://www.anaconda.com/download/">发行版</a>为您处理如Numpy, Sympy, Scipy等软件包依赖项提供了一种简便的方法。</p>
<p>你可以参考 <a href="/archives/deploy-anaconda-on-windows/" title="这篇文章">这篇文章</a> 来部署Anaconda。</p>
<h3 id="Sympy先决条件">Sympy先决条件</h3>
<p><strong>SymPy</strong>是一个符号计算的<a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/Python">Python</a><a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/%E5%BA%93_(%E8%AE%A1%E7%AE%97%E6%9C%BA)">库</a>。它的目标是成为一个全功能的<a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/%E8%AE%A1%E7%AE%97%E6%9C%BA%E4%BB%A3%E6%95%B0%E7%B3%BB%E7%BB%9F">计算机代数系统</a>，同时保持代码简洁、易于理解和扩展。支持符号计算、<a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/%E9%AB%98%E7%B2%BE%E5%BA%A6%E8%AE%A1%E7%AE%97">高精度计算</a>、模式匹配、绘图、解方程、微积分、<a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/%E7%BB%84%E5%90%88%E6%95%B0%E5%AD%A6">组合数学</a>、<a target="_blank" rel="noopener" href="https://zh.wikipedia.org/wiki/%E7%A6%BB%E6%95%A3%E6%95%B0%E5%AD%A6">离散数学</a>、几何学、概率与统计、物理学等方面的功能。</p>
<p>在开始用Sympy求解微分方程之前，不妨先入门一下Sympy。</p>
<h2 id="求微分方程通解">求微分方程通解</h2>
<p>以初值问题：</p>
<p><span class="katex-display"><span class="katex"><span class="katex-mathml"><math xmlns="http://www.w3.org/1998/Math/MathML" display="block"><semantics><mrow><msup><mi>y</mi><mrow><mo mathvariant="normal">′</mo><mo mathvariant="normal">′</mo></mrow></msup><mo>+</mo><mn>2</mn><msup><mi>y</mi><mo mathvariant="normal" lspace="0em" rspace="0em">′</mo></msup><mo>+</mo><mn>2</mn><mi>y</mi><mo>=</mo><mi>x</mi><msup><mi>e</mi><mrow><mo>−</mo><mi>x</mi></mrow></msup><mo separator="true">,</mo><mspace width="1em"/><mi>y</mi><mo stretchy="false">(</mo><mn>0</mn><mo stretchy="false">)</mo><mo>=</mo><msup><mi>y</mi><mo mathvariant="normal" lspace="0em" rspace="0em">′</mo></msup><mo stretchy="false">(</mo><mn>0</mn><mo stretchy="false">)</mo><mo>=</mo><mn>0</mn></mrow><annotation encoding="application/x-tex">y&#x27;&#x27;+2y&#x27;+2y=xe^{-x}, \quad y(0)=y&#x27;(0)=0
</annotation></semantics></math></span><span class="katex-html" aria-hidden="true"><span class="base"><span class="strut" style="height:0.996332em;vertical-align:-0.19444em;"></span><span class="mord"><span class="mord mathnormal" style="margin-right:0.03588em;">y</span><span class="msupsub"><span class="vlist-t"><span class="vlist-r"><span class="vlist" style="height:0.801892em;"><span style="top:-3.113em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">′</span><span class="mord mtight">′</span></span></span></span></span></span></span></span></span><span class="mspace" style="margin-right:0.2222222222222222em;"></span><span class="mbin">+</span><span class="mspace" style="margin-right:0.2222222222222222em;"></span></span><span class="base"><span class="strut" style="height:0.996332em;vertical-align:-0.19444em;"></span><span class="mord">2</span><span class="mord"><span class="mord mathnormal" style="margin-right:0.03588em;">y</span><span class="msupsub"><span class="vlist-t"><span class="vlist-r"><span class="vlist" style="height:0.801892em;"><span style="top:-3.113em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">′</span></span></span></span></span></span></span></span></span><span class="mspace" style="margin-right:0.2222222222222222em;"></span><span class="mbin">+</span><span class="mspace" style="margin-right:0.2222222222222222em;"></span></span><span class="base"><span class="strut" style="height:0.8388800000000001em;vertical-align:-0.19444em;"></span><span class="mord">2</span><span class="mord mathnormal" style="margin-right:0.03588em;">y</span><span class="mspace" style="margin-right:0.2777777777777778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2777777777777778em;"></span></span><span class="base"><span class="strut" style="height:1.071331em;vertical-align:-0.25em;"></span><span class="mord mathnormal">x</span><span class="mord"><span class="mord mathnormal">e</span><span class="msupsub"><span class="vlist-t"><span class="vlist-r"><span class="vlist" style="height:0.821331em;"><span style="top:-3.113em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">−</span><span class="mord mathnormal mtight">x</span></span></span></span></span></span></span></span></span><span class="mpunct">,</span><span class="mspace" style="margin-right:1em;"></span><span class="mspace" style="margin-right:0.16666666666666666em;"></span><span class="mord mathnormal" style="margin-right:0.03588em;">y</span><span class="mopen">(</span><span class="mord">0</span><span class="mclose">)</span><span class="mspace" style="margin-right:0.2777777777777778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2777777777777778em;"></span></span><span class="base"><span class="strut" style="height:1.051892em;vertical-align:-0.25em;"></span><span class="mord"><span class="mord mathnormal" style="margin-right:0.03588em;">y</span><span class="msupsub"><span class="vlist-t"><span class="vlist-r"><span class="vlist" style="height:0.801892em;"><span style="top:-3.113em;margin-right:0.05em;"><span class="pstrut" style="height:2.7em;"></span><span class="sizing reset-size6 size3 mtight"><span class="mord mtight"><span class="mord mtight">′</span></span></span></span></span></span></span></span></span><span class="mopen">(</span><span class="mord">0</span><span class="mclose">)</span><span class="mspace" style="margin-right:0.2777777777777778em;"></span><span class="mrel">=</span><span class="mspace" style="margin-right:0.2777777777777778em;"></span></span><span class="base"><span class="strut" style="height:0.64444em;vertical-align:0em;"></span><span class="mord">0</span></span></span></span></span></p>
<p>为例。</p>
<p><code>get-general-solution.py</code>可以求出微分方程的通解：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> sympy <span class="keyword">as</span> sy</span><br><span class="line"></span><br><span class="line">f = sy.symbols(<span class="string">&#x27;f&#x27;</span>, cls=sy.Function)</span><br><span class="line">x = sy.symbols(<span class="string">&#x27;x&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 在这里输入你要求解的微分方程，逗号前输入左式，逗号后输入右式</span></span><br><span class="line"><span class="comment"># 若包含exp(), sin()等函数，请写成sy.exp(), sy.sin()等</span></span><br><span class="line">differential_equation = sy.Eq(</span><br><span class="line">    f(x).diff(x, <span class="number">2</span>) + <span class="number">2</span> * f(x).diff(x, <span class="number">1</span>) + <span class="number">2</span> * f(x), x * sy.exp(-x))</span><br><span class="line"></span><br><span class="line">general_solution = sy.dsolve(differential_equation, f(x)).rhs</span><br><span class="line"></span><br><span class="line">print(general_solution)</span><br></pre></td></tr></table></figure>
<p><code>[out]</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">(C1*sin(x) + C2*cos(x) + x)*exp(-x)</span><br></pre></td></tr></table></figure>
<h2 id="解初值问题">解初值问题</h2>
<p><code>get-particular-solution.py</code>可以求出微分方程的特解：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> sympy <span class="keyword">as</span> sy</span><br><span class="line"></span><br><span class="line">x = sy.symbols(<span class="string">&#x27;x&#x27;</span>)</span><br><span class="line"></span><br><span class="line">C1 = sy.symbols(<span class="string">&#x27;C1&#x27;</span>)</span><br><span class="line">C2 = sy.symbols(<span class="string">&#x27;C2&#x27;</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 在这里输入由get-general-solution.py获得的微分方程通解</span></span><br><span class="line"><span class="comment"># 如果出现C3, C4等参数，请在上方加入形如C3 = sy.symbols(&#x27;C3&#x27;)等语句</span></span><br><span class="line"><span class="comment"># 若包含exp(), sin()等函数，请写成sy.exp(), sy.sin()等</span></span><br><span class="line">general_solution = (C1*sy.sin(x) + C2*sy.cos(x) + x)*sy.exp(-x)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 求解C1, C2等的值，</span></span><br><span class="line"><span class="comment"># 如果初值条件右式不为零，请移项至左边，使得右式为0</span></span><br><span class="line"><span class="comment"># 如果含更多初值条件，请加入形如:</span></span><br><span class="line"><span class="comment"># f3 = general_solution.diff(x, 2).subs(x, 0)</span></span><br><span class="line"><span class="comment"># 等语句，diff(x, n)表示通解对x求n阶导</span></span><br><span class="line">f1 = general_solution.subs(x, <span class="number">0</span>)</span><br><span class="line">f2 = general_solution.diff(x, <span class="number">1</span>).subs(x, <span class="number">0</span>)</span><br><span class="line">parameters = sy.solve([f1, f2], [C1, C2])</span><br><span class="line"></span><br><span class="line"><span class="comment"># 如果含有C3，请添加形如：</span></span><br><span class="line"><span class="comment"># particular_solution = particular_solution.subs(C3, parameters[C3])</span></span><br><span class="line"><span class="comment"># 等语句</span></span><br><span class="line">particular_solution = general_solution</span><br><span class="line">particular_solution = particular_solution.subs(C1, parameters[C1])</span><br><span class="line">particular_solution = particular_solution.subs(C2, parameters[C2])</span><br><span class="line"></span><br><span class="line">print(particular_solution)</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p><code>[out]</code></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">(x - sin(x))*exp(-x)</span><br></pre></td></tr></table></figure>
<h2 id="绘制函数图像">绘制函数图像</h2>
<p><code>get-function-graph.py</code>可以绘制特解函数的图像：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> sympy <span class="keyword">as</span> sy</span><br><span class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> plt</span><br><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"></span><br><span class="line"><span class="comment"># 在这里输入由get-particular-solution.py获得的微分方程特解</span></span><br><span class="line"><span class="comment"># 若包含exp(), sin()等函数，请写成sy.exp(), sy.sin()等</span></span><br><span class="line">x = sy.symbols(<span class="string">&#x27;x&#x27;</span>)</span><br><span class="line">particular_solution = (x - sy.sin(x))*sy.exp(-x)</span><br><span class="line"></span><br><span class="line">x_range = np.arange(-<span class="number">5</span>, <span class="number">5</span>, <span class="number">0.1</span>)	//np.arange(a, b, step)表示绘制的区间和步长</span><br><span class="line">y_range = [particular_solution.subs(x, x_val) <span class="keyword">for</span> x_val <span class="keyword">in</span> x_range]</span><br><span class="line">plt.plot(x_range, y_range)</span><br><span class="line">plt.axis([-<span class="number">6</span>, <span class="number">6</span>, -<span class="number">10</span>, <span class="number">10</span>])	//axis([x1, x2, y1, y2])表示在[x1, x2], [y1, y2]范围内绘图</span><br><span class="line">plt.grid()</span><br><span class="line">plt.show()</span><br></pre></td></tr></table></figure>
<p><code>[out]</code></p>
<p><img src= "" data-lazy-src="https://z3.ax1x.com/2021/04/26/gScakQ.png" alt="gScakQ.png"></p>
<h2 id="请参见">请参见</h2>
<ul>
<li><a target="_blank" rel="noopener" href="https://blog.csdn.net/cj151525/article/details/95756847">https://blog.csdn.net/cj151525/article/details/95756847</a></li>
<li><a target="_blank" rel="noopener" href="https://www.jb51.net/article/185664.htm">https://www.jb51.net/article/185664.htm</a></li>
<li>
<a href="/archives/deploy-anaconda-on-windows/" title="Anaconda部署与使用指南（Windows）">Anaconda部署与使用指南（Windows）</a> </li>
</ul>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">Von Brank</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://vonbrank.github.io/archives/sympy-solve-differential-equation/">https://vonbrank.github.io/archives/sympy-solve-differential-equation/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://vonbrank.github.io" target="_blank">Von Brank</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/%E6%95%99%E7%A8%8B/">教程</a><a class="post-meta__tags" href="/tags/Python/">Python</a></div><div class="post_share"><div class="social-share" data-image="https://z3.ax1x.com/2021/04/26/gSWYgs.md.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><div class="post-reward"><div class="reward-button button--animated"><i class="fas fa-qrcode"></i> 打赏</div><div class="reward-main"><ul class="reward-all"><li class="reward-item"><a href="/img/wechat.png" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="/img/wechat.png" alt="WeChat"/></a><div class="post-qr-code-desc">WeChat</div></li><li class="reward-item"><a href="/img/alipay.jpg" target="_blank"><img class="post-qr-code-img" src= "" data-lazy-src="/img/alipay.jpg" alt="AliPay"/></a><div class="post-qr-code-desc">AliPay</div></li></ul></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/archives/hit-note-ma21004/"><img class="prev-cover" src= "" data-lazy-src="https://z3.ax1x.com/2021/04/27/g956YV.md.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">HIT | 工科数学分析 | 课程笔记 | 2021春季</div></div></a></div><div class="next-post pull-right"><a href="/archives/codeforces-solution-round-709-div-2/"><img class="next-cover" src= "" data-lazy-src="https://z3.ax1x.com/2021/03/25/6LxXpq.png" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">【Codeforces】 题解 - Round 709 (Div.2)</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/archives/cs231n-preparation/" title="CS231n | 先决条件 Preparation"><img class="cover" src= "" data-lazy-src="https://z3.ax1x.com/2021/03/21/64GeH0.md.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-03-21</div><div class="title">CS231n | 先决条件 Preparation</div></div></a></div><div><a href="/archives/deploy-anaconda-on-windows/" title="Anaconda部署与使用指南（Windows）"><img class="cover" src= "" data-lazy-src="https://s3.ax1x.com/2021/03/13/6w8xDP.md.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-03-13</div><div class="title">Anaconda部署与使用指南（Windows）</div></div></a></div><div><a href="/archives/cs231n-assignment1-knn/" title="CS231n | 课程作业 Assignment1 | K近邻算法 KNN"><img class="cover" src= "" data-lazy-src="https://z3.ax1x.com/2021/03/21/64GeH0.md.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-03-22</div><div class="title">CS231n | 课程作业 Assignment1 | K近邻算法 KNN</div></div></a></div><div><a href="/archives/hit-cs31106-explanation-04/" title="C语言答疑-04"><img class="cover" src= "" data-lazy-src="https://s2.loli.net/2022/01/08/aHnR1gNZI75hTd2.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2020-11-23</div><div class="title">C语言答疑-04</div></div></a></div><div><a href="/archives/hit-software-construction-lab1-config/" title="HIT-软件构造 | Lab1 项目配置"><img class="cover" src= "" data-lazy-src="https://s2.loli.net/2022/05/01/pZiMB5ED7aHY3G4.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-04-29</div><div class="title">HIT-软件构造 | Lab1 项目配置</div></div></a></div><div><a href="/archives/std-checker/" title="在Windows下编写C++对拍程序（真随机数）"><img class="cover" src= "" data-lazy-src="https://z3.ax1x.com/2021/03/28/cStdW6.md.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-03-28</div><div class="title">在Windows下编写C++对拍程序（真随机数）</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "" data-lazy-src="https://s2.loli.net/2022/01/08/s8FYlS5uPrtichT.jpg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">Von Brank</div><div class="author-info__description">Von Brank, a student from Harbin Institute of Technology, who likes coding, video editing, designing, gaming, and more.</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">46</div></a></div><div class="card-info-data-item is-center"><a href="/tags/"><div class="headline">标签</div><div class="length-num">25</div></a></div><div class="card-info-data-item is-center"><a href="/categories/"><div class="headline">分类</div><div class="length-num">19</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/vonbrank"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/vonbrank" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="mailto:vonbrank@outlook.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a><a class="social-icon" href="https://twitter.com/Von_Brank" target="_blank" title="Twitter"><i class="fab fa-twitter"></i></a><a class="social-icon" href="https://steamcommunity.com/id/vonbrank/" target="_blank" title="Steam"><i class="fab fa-steam"></i></a><a class="social-icon" href="/atom.xml" target="_blank" title="RSS"><i class="fas fa-rss"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%85%88%E5%86%B3%E6%9D%A1%E4%BB%B6"><span class="toc-text">先决条件</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#Anaconda%E5%85%88%E5%86%B3%E6%9D%A1%E4%BB%B6"><span class="toc-text">Anaconda先决条件</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Sympy%E5%85%88%E5%86%B3%E6%9D%A1%E4%BB%B6"><span class="toc-text">Sympy先决条件</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B1%82%E5%BE%AE%E5%88%86%E6%96%B9%E7%A8%8B%E9%80%9A%E8%A7%A3"><span class="toc-text">求微分方程通解</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%A7%A3%E5%88%9D%E5%80%BC%E9%97%AE%E9%A2%98"><span class="toc-text">解初值问题</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BB%98%E5%88%B6%E5%87%BD%E6%95%B0%E5%9B%BE%E5%83%8F"><span class="toc-text">绘制函数图像</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%AF%B7%E5%8F%82%E8%A7%81"><span class="toc-text">请参见</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/archives/hit-software-construction-lab1-config/" title="HIT-软件构造 | Lab1 项目配置"><img src= "" data-lazy-src="https://s2.loli.net/2022/05/01/pZiMB5ED7aHY3G4.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="HIT-软件构造 | Lab1 项目配置"/></a><div class="content"><a class="title" href="/archives/hit-software-construction-lab1-config/" title="HIT-软件构造 | Lab1 项目配置">HIT-软件构造 | Lab1 项目配置</a><time datetime="2022-04-29T09:37:16.000Z" title="发表于 2022-04-29 17:37:16">2022-04-29</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/archives/book-note-csapp/" title="【阅读笔记】深入理解计算机系统"><img src= "" data-lazy-src="https://s2.loli.net/2022/01/12/DuW9EMYc274VsvS.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="【阅读笔记】深入理解计算机系统"/></a><div class="content"><a class="title" href="/archives/book-note-csapp/" title="【阅读笔记】深入理解计算机系统">【阅读笔记】深入理解计算机系统</a><time datetime="2022-01-12T06:13:00.000Z" title="发表于 2022-01-12 14:13:00">2022-01-12</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/archives/udemy-note-the-complete-javascript-course/" title="【课程笔记】Udemy - The Complete JavaScript Course 2022: From Zero to Expert!"><img src= "" data-lazy-src="https://s2.loli.net/2022/01/07/IpZeyLJzvVwbO7A.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="【课程笔记】Udemy - The Complete JavaScript Course 2022: From Zero to Expert!"/></a><div class="content"><a class="title" href="/archives/udemy-note-the-complete-javascript-course/" title="【课程笔记】Udemy - The Complete JavaScript Course 2022: From Zero to Expert!">【课程笔记】Udemy - The Complete JavaScript Course 2022: From Zero to Expert!</a><time datetime="2022-01-07T16:13:32.000Z" title="发表于 2022-01-08 00:13:32">2022-01-08</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/archives/udemy-note-advanced-css-and-sass/" title="【课程笔记】Udemy - Advanced CSS and Sass: Flexbox, Grid, Animations and More!"><img src= "" data-lazy-src="https://s2.loli.net/2022/01/07/AKhDvulVjkErmXS.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="【课程笔记】Udemy - Advanced CSS and Sass: Flexbox, Grid, Animations and More!"/></a><div class="content"><a class="title" href="/archives/udemy-note-advanced-css-and-sass/" title="【课程笔记】Udemy - Advanced CSS and Sass: Flexbox, Grid, Animations and More!">【课程笔记】Udemy - Advanced CSS and Sass: Flexbox, Grid, Animations and More!</a><time datetime="2022-01-07T12:44:32.000Z" title="发表于 2022-01-07 20:44:32">2022-01-07</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/archives/udemy-note-build-responsive-real-world-websites-with-html-and-css/" title="【课程笔记】Udemy - Build Responsive Real-World Websites with HTML and CSS"><img src= "" data-lazy-src="https://s2.loli.net/2022/01/07/8O5MjcQI7peF6CK.jpg" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="【课程笔记】Udemy - Build Responsive Real-World Websites with HTML and CSS"/></a><div class="content"><a class="title" href="/archives/udemy-note-build-responsive-real-world-websites-with-html-and-css/" title="【课程笔记】Udemy - Build Responsive Real-World Websites with HTML and CSS">【课程笔记】Udemy - Build Responsive Real-World Websites with HTML and CSS</a><time datetime="2022-01-05T14:31:56.000Z" title="发表于 2022-01-05 22:31:56">2022-01-05</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://z3.ax1x.com/2021/04/26/gSWYgs.md.png')"><div id="footer-wrap"><div class="copyright">&copy;2021 - 2022 By Von Brank</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div></div><hr/><div id="local-search-results"></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script src="/js/search/local-search.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"><link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/katex@latest/dist/katex.min.css"><script src="https://cdn.jsdelivr.net/npm/katex-copytex@latest/dist/katex-copytex.min.js"></script><link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/katex-copytex@latest/dist/katex-copytex.min.css"><script>(() => {
  document.querySelectorAll('#article-container span.katex-display').forEach(item => {
    btf.wrap(item, 'div', { class: 'katex-wrap'})
  })
})()</script></div><script id="canvas_nest" defer="defer" color="27, 129, 203" opacity="0.7" zIndex="-1" count="256" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-nest.min.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>